import json
from constr_budgets.models import People, Modules
from django.http import JsonResponse
import jwt
import time
from utils.Infinite import infinite


# 登录
def login(req):
    data = req.body
    da = json.loads(req.body)
    d = {
        'exp': time.time() + 30000,
        'iat': time.time(),
        'iss': 'Issuer',
        'data': {
            'username': da["phone"],
            'timestamp': time.time()
        }
    }
    jwt_encode = jwt.encode(d, data, algorithm="HS256")
    try:
        li = list(People.objects.filter(phone=da["phone"]).values("id", "name", "password", "phone", "peopleState",
                                                                  "entryTime", "role_auth", "people_id"))[0]
        if li["peopleState"]:
            if da["password"] == li["password"]:
                People.objects.filter(phone=da["phone"]).update(token=jwt_encode, end_token=d["exp"])
                tokens = list(People.objects.filter(phone=da["phone"]).values("token", "people_id__rank"))
                # if tokens[0]["token"] == "3":
                return JsonResponse({"code": 200, "msg": "登陆成功", "token": tokens[0]["token"],
                                     "rank": tokens[0]["people_id__rank"], "info": li})
            elif da["password"] != li["password"]:
                return JsonResponse({"code": 403, "msg": "密码错误"})
        else:
            return JsonResponse({"code": 403, "msg": "该用户已禁用"})
    except IndexError:
        return JsonResponse({"code": 403, "msg": "没有找到该用户"})
    return JsonResponse({"code": 500, "msg": "服务端错误"})


# 自动登录
def logins(req):
    token = req.META.get("HTTP_AUTHORIZATION").split(" ")[1]
    try:
        li = list(People.objects.filter(token=token).values())[0]
        if float(li["end_token"]) < time.time():
            return JsonResponse({"code": 403, "msg": "token过期"})
        else:
            return JsonResponse({"code": 200, "token": li["token"]})
    except IndexError:
        return JsonResponse({"code": 200, "msg": "没有找到token"})
